package cn.kongwg.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author kongwg
 * @create 2021-03-12 17:08
 */
@RestController
public class UpDwlController {
    // @RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
    // 批量上传CommonsMultipartFile则为数组即可
    @RequestMapping("/upload")
    public String fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

        //获取文件的真是名字
        String filename = file.getOriginalFilename();

        //上传的路径
        File realPath = new File("F:/upload");

        //判断上传的路径是否存在
        if (!realPath.exists()) {
            realPath.mkdir();
        }

        try {
            //将文件存到指定的位置
            file.transferTo(new File(realPath + "/" + filename));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }

        return "upload ok";
    }

    @RequestMapping("/dow")
    public String dow(HttpServletResponse response) {

        FileInputStream fis = null;
        ServletOutputStream sos = null;
        try {
            //下载文件的名字
            String fileName = "孔.png";

            response.reset();//清除缓存
            response.setCharacterEncoding("utf-8");//设置字符编码
            response.setContentType("multipart/form-data");//下载方式使用二进制

            //下载文件的名字使用中文时不出现乱码
            response.setHeader("Content-Disposition", "attachment;fileName=" +
                    URLEncoder.encode(fileName, "UTF-8"));

            //输入流
            fis = new FileInputStream("F:/upload/" + fileName);

            //输出流
            sos = response.getOutputStream();

            //将输入流拷贝进输出流中
            IOUtils.copy(fis, sos);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (sos != null) {
                try {
                    sos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

        return "dowload ok";

    }
}
